{% extends "base.html" %}

{% block title %}环境详情 - API场景组合测试工具{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>环境详情</h2>
    <div>
        <a href="{{ url_for('environment.list_environments') }}" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> 返回列表
        </a>
        <button type="button" class="btn btn-warning edit-env-btn" 
                data-env-id="{{ environment.id }}" 
                data-env-name="{{ environment.name }}" 
                data-env-base-url="{{ environment.base_url }}" 
                data-env-description="{{ environment.description }}">
            <i class="fas fa-edit"></i> 编辑
        </button>
        <button type="button" class="btn btn-danger delete-env-btn" data-env-id="{{ environment.id }}">
            <i class="fas fa-trash"></i> 删除
        </button>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5>基本信息</h5>
            </div>
            <div class="card-body">
                <table class="table">
                    <tr>
                        <th style="width: 30%">ID</th>
                        <td>{{ environment.id }}</td>
                    </tr>
                    <tr>
                        <th>名称</th>
                        <td>{{ environment.name }}</td>
                    </tr>
                    <tr>
                        <th>基础URL</th>
                        <td>{{ environment.base_url }}</td>
                    </tr>
                    <tr>
                        <th>描述</th>
                        <td>{{ environment.description }}</td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5>认证信息</h5>
            </div>
            <div class="card-body">
                <div id="auth-status">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span id="auth-status-text">正在检查认证状态...</span>
                        <div>
                            <button class="btn btn-sm btn-success" id="refresh-auth-btn">
                                <i class="fas fa-sync"></i> 刷新
                            </button>
                            <button class="btn btn-sm btn-danger" id="invalidate-auth-btn">
                                <i class="fas fa-times"></i> 使认证失效
                            </button>
                        </div>
                    </div>
                    <div id="auth-details" class="d-none">
                        <div class="mb-2">
                            <strong>创建时间:</strong> <span id="auth-created-at"></span>
                        </div>
                        <div class="mb-2">
                            <strong>过期时间:</strong> <span id="auth-expires-at"></span>
                        </div>
                        <div>
                            <strong>认证数据:</strong>
                            <pre id="auth-data" class="mt-2 p-2 bg-light" style="max-height: 200px; overflow-y: auto;"></pre>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5>配置</h5>
            </div>
            <div class="card-body">
                <pre id="config-json" class="p-2 bg-light" style="max-height: 300px; overflow-y: auto;">{{ environment.config|tojson(indent=2) }}</pre>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5>认证配置</h5>
            </div>
            <div class="card-body">
                <pre id="auth-config-json" class="p-2 bg-light" style="max-height: 300px; overflow-y: auto;">{{ environment.auth_config|tojson(indent=2) }}</pre>
            </div>
        </div>
    </div>
</div>

<!-- 编辑环境模态框 -->
<div class="modal fade" id="editEnvModal" tabindex="-1" aria-labelledby="editEnvModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editEnvModalLabel">编辑环境</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editEnvForm">
                    <input type="hidden" id="edit_env_id" name="env_id">
                    <div class="mb-3">
                        <label for="edit_name" class="form-label">环境名称</label>
                        <input type="text" class="form-control" id="edit_name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_base_url" class="form-label">基础URL</label>
                        <input type="text" class="form-control" id="edit_base_url" name="base_url" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_description" class="form-label">描述</label>
                        <textarea class="form-control" id="edit_description" name="description" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="edit_config" class="form-label">配置 (JSON)</label>
                        <textarea class="form-control" id="edit_config" name="config" rows="5"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="edit_auth_config" class="form-label">认证配置 (JSON)</label>
                        <textarea class="form-control" id="edit_auth_config" name="auth_config" rows="5"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="updateEnvBtn">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteEnvModal" tabindex="-1" aria-labelledby="deleteEnvModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteEnvModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个环境吗？此操作不可撤销。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteEnvBtn">删除</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    $(document).ready(function() {
        // 格式化JSON显示
        try {
            const configJson = JSON.parse($('#config-json').text());
            $('#config-json').text(JSON.stringify(configJson, null, 2));
        } catch (e) {
            $('#config-json').text('{}');
        }
        
        try {
            const authConfigJson = JSON.parse($('#auth-config-json').text());
            $('#auth-config-json').text(JSON.stringify(authConfigJson, null, 2));
        } catch (e) {
            $('#auth-config-json').text('{}');
        }
        
        // 加载认证状态
        function loadAuthStatus() {
            $.ajax({
                url: '/environment/{{ environment.id }}/auth',
                type: 'GET',
                success: function(response) {
                    if (response.success) {
                        $('#auth-status-text').html('<span class="text-success"><i class="fas fa-check-circle"></i> 认证有效</span>');
                        $('#auth-details').removeClass('d-none');
                        $('#auth-created-at').text(response.created_at);
                        $('#auth-expires-at').text(response.expires_at || '永不过期');
                        $('#auth-data').text(JSON.stringify(response.auth_data, null, 2));
                    } else {
                        $('#auth-status-text').html('<span class="text-danger"><i class="fas fa-times-circle"></i> 认证无效或过期</span>');
                        $('#auth-details').addClass('d-none');
                    }
                },
                error: function() {
                    $('#auth-status-text').html('<span class="text-danger"><i class="fas fa-exclamation-circle"></i> 获取认证状态失败</span>');
                    $('#auth-details').addClass('d-none');
                }
            });
        }
        
        // 初始加载认证状态
        loadAuthStatus();
        
        // 刷新认证状态
        $('#refresh-auth-btn').click(function() {
            loadAuthStatus();
        });
        
        // 使认证失效
        $('#invalidate-auth-btn').click(function() {
            if (confirm('确定要使当前认证失效吗？')) {
                $.ajax({
                    url: '/environment/{{ environment.id }}/auth/invalidate',
                    type: 'POST',
                    success: function(response) {
                        if (response.success) {
                            alert('认证已成功失效');
                            loadAuthStatus();
                        } else {
                            alert('操作失败: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('请求失败，请稍后重试');
                    }
                });
            }
        });
        
        // 打开编辑模态框
        $('.edit-env-btn').click(function() {
            const envId = $(this).attr('data-env-id');
            const envName = $(this).attr('data-env-name');
            const envBaseUrl = $(this).attr('data-env-base-url');
            const envDescription = $(this).attr('data-env-description');
            
            $('#edit_env_id').val(envId);
            $('#edit_name').val(envName);
            $('#edit_base_url').val(envBaseUrl);
            $('#edit_description').val(envDescription);
            $('#edit_config').val($('#config-json').text());
            $('#edit_auth_config').val($('#auth-config-json').text());
            
            $('#editEnvModal').modal('show');
        });
        
        // 更新环境
        $('#updateEnvBtn').click(function() {
            const envId = $('#edit_env_id').val();
            const formData = {
                name: $('#edit_name').val(),
                base_url: $('#edit_base_url').val(),
                description: $('#edit_description').val(),
                config: $('#edit_config').val(),
                auth_config: $('#edit_auth_config').val()
            };
            
            $.ajax({
                url: '/environment/' + envId,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    if (response.success) {
                        alert('环境更新成功');
                        location.reload();
                    } else {
                        alert('更新失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        });
        
        // 打开删除确认模态框
        $('.delete-env-btn').click(function() {
            const envId = $(this).attr('data-env-id');
            $('#confirmDeleteEnvBtn').attr('data-env-id', envId);
            $('#deleteEnvModal').modal('show');
        });
        
        // 确认删除环境
        $('#confirmDeleteEnvBtn').click(function() {
            const envId = $(this).attr('data-env-id');
            $.ajax({
                url: '/environment/' + envId,
                type: 'DELETE',
                success: function(response) {
                    if (response.success) {
                        alert('环境删除成功');
                        window.location.href = '{{ url_for("environment.list_environments") }}';
                    } else {
                        alert('删除失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        });
        
        // 验证JSON输入
        function validateJsonInput(input) {
            try {
                const value = $(input).val();
                if (value) {
                    JSON.parse(value);
                    $(input).removeClass('is-invalid');
                }
            } catch (e) {
                $(input).addClass('is-invalid');
                return false;
            }
            return true;
        }
        
        $('#edit_config, #edit_auth_config').blur(function() {
            validateJsonInput(this);
        });
        
        // 表单提交前验证
        $('#updateEnvBtn').click(function(e) {
            if (!validateJsonInput('#edit_config') || !validateJsonInput('#edit_auth_config')) {
                e.preventDefault();
                alert('请检查JSON格式是否正确');
                return false;
            }
        });
    });
</script>
{% endblock %}